<template>
  <!-- 侧边导航菜单，支持折叠 -->
  <el-menu
    :default-active="activeMenu"
    class="el-menu-vertical-demo navbar"
    :collapse="isCollapse"
    router
  >
    <template v-for="(item, index) in menuData" :key="index">
      <!-- 普通菜单项 -->
      <el-menu-item v-if="!item.children" :index="item.path">
        <el-icon>
          <component :is="item.icon" />
        </el-icon>
        <template #title>{{ item.title }}</template>
      </el-menu-item>

      <!-- 带子菜单的菜单项 -->
      <el-sub-menu v-else :index="item.path">
        <template #title>
          <el-icon>
            <component :is="item.icon" />
          </el-icon>
          <span>{{ item.title }}</span>
        </template>
        <el-menu-item-group>
          <el-menu-item
            v-for="(child, childIndex) in item.children"
            :key="childIndex"
            :index="child.path"
          >
            {{ child.title }}
          </el-menu-item>
        </el-menu-item-group>
      </el-sub-menu>
    </template>
  </el-menu>
</template>

<script setup>
// 引入 vue 相关方法
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
// 引入 Element Plus 菜单相关组件
import { ElMenu, ElMenuItem, ElSubMenu, ElIcon, ElMenuItemGroup } from 'element-plus'
// 引入图标
import { HomeFilled, User, Avatar, Notebook, DataLine, Setting } from '@element-plus/icons-vue'

// 父组件传递的折叠状态
const props = defineProps({
  isCollapse: Boolean,
})

// 当前激活菜单项
const route = useRoute()
const activeMenu = ref(route.path)

// 监听路由变化，更新 activeMenu
watch(() => route.path, (newPath) => {
  activeMenu.value = newPath
})

// 菜单数据结构，可扩展 children 实现多级菜单
const menuData = [
  {
    path: '/dashboard',
    icon: HomeFilled,
    title: '首页',
  },
  {
    path: '/dashboard/user',
    icon: User,
    title: '用户管理',
  },
  {
    path: '/dashboard/role',
    icon: Avatar,
    title: '角色管理',
  },
  {
    path: '/dashboard/content',
    icon: Notebook,
    title: '内容管理',
  },
  {
    path: '/dashboard/data',
    icon: DataLine,
    title: '数据管理',
  },
  {
    path: '/dashboard/system/settings',
    icon: Setting,
    title: '系统设置',
  },
]
</script>

<style scoped>
/* 展开时菜单宽度 */
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}

/* 导航栏高度自适应 */
.navbar {
  height: 100%;
}
</style>